<?php
/**
 * Created by PhpStorm.
 * User: fengzi
 * Date: 2019/6/3
 * Time: 14:34
 */

namespace app\vehicle\logic;
use think\Db;
use app\vehicle\model\Order;
use app\vehicle\model\Delivery;
use app\vehicle\model\DeliveryBus;
use app\vehicle\model\OrderPrice;
class deliveryLogic{
    //获取投递列表
    public function getDeliveryList($data,$user){
        $where = [
            ['order_id','eq',$data['id']],
            ['status','lt',2]
        ];
        $list = Delivery::with(['business','bus_list','price'])->where($where)->page($data['page'],100)->select();
        return $list;
    }
    //获取已选择投递列表
    public function getOrderDeliveryList($order_id){
        $where = [
            ['order_id','eq',$order_id],
            ['status','eq',2]
        ];
        $list = Delivery::with(['business','bus_list','price'])->where($where)->select();
        return $list;
    }
    //确认订单
    public function confirmDeliveryInfo($data,$user){
        $order_info = Order::get($data['order_id']);
        if(!$data['signature_id']){
            return '请选择签名';
        }
        Db::startTrans();
        try {
            $up['status'] = 1;
            $delivery_id = ltrim($data['delivery_id'],',');
            $delivery_bus = DeliveryBus::where('id','in',$delivery_id)->where('status','eq',2)->find();
            if($delivery_bus['id']){
                $bus_no = Bus::where('id','eq',$delivery_bus['bus_id'])->value('bus_no');
                return $bus_no.'该车辆已被预订';
            }
            DeliveryBus::where('id','in',$delivery_id)->update($up);
            $did = DeliveryBus::where('id','in',$delivery_id)->group('order_id')->column('delivery_id');
            $prev_id = implode($did,',');
            Delivery::where('id','in',$prev_id)->update(['status'=>1]);
            //修改订单状态
            Order::where('id','eq',$data['order_id'])->update(['status'=>1,'signature_id'=>$data['signature_id']]);
            //确认订单金额
            //$price['pay_price'] = Delivery::where('id','in',$prev_id)->sum('price');
            $price['pay_price'] = DeliveryBus::alias('as db')
                ->join(config('database.prefix').'delivery d','d.id=db.delivery_id')
                ->where('db.id','in',$delivery_id)
                ->sum('d.price');
            OrderPrice::where('order_id','eq',$data['order_id'])->update($price);

            Db::commit();
            return 1;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return 0;
        }
    }
}